package zcrypto

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/base64"
	"fmt"
)

func DesEncrypt(src string, key string) string {
	bKey := []byte(key)
	bSrc := []byte(src)
	block, e := des.NewCipher(bKey)
	if e != nil {
		fmt.Println(e)
		return ""
	}

	bSrc = padding(bSrc, block.BlockSize())

	blockMode := cipher.NewCBCEncrypter(block, bKey)
	out := make([]byte, len(bSrc))
	blockMode.CryptBlocks(out, bSrc)
	return base64.StdEncoding.EncodeToString(out)

}

func DesEncryptECB(src, key string) string {
	data := []byte(src)
	keyByte := []byte(key)
	block, err := des.NewCipher(keyByte)
	if err != nil {
		panic(err)
	}
	bs := block.BlockSize()
	//对明文数据进行补码
	data = padding(data, bs)
	if len(data)%bs != 0 {
		panic("Need a multiple of the block size")
	}
	out := make([]byte, len(data))
	dst := out
	for len(data) > 0 {
		//对明文按照block size进行分块加密
		//必要时可以使用go关键字进行并行加密
		block.Encrypt(dst, data[:bs])
		data = data[bs:]
		dst = dst[bs:]
	}
	//fmt.Printf("%x", out)
	return base64.StdEncoding.EncodeToString(out)
}

// 明文补码算法
func padding(ciphertext []byte, blockSize int) []byte {
	padding_ := blockSize - len(ciphertext)%blockSize
	padText := bytes.Repeat([]byte{byte(padding_)}, padding_)
	return append(ciphertext, padText...)
}

// 明文减码算法
func unPadding(origData []byte) []byte {
	length := len(origData)
	unPadding_ := int(origData[length-1])
	return origData[:(length - unPadding_)]
}
